package com.qianli.cashmama.trade.integration.notification.message.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.common.utils.TimeUtils;
import com.fqgj.msg.email.EmailSendService;
import com.fqgj.msg.enums.BuryingPointServicerEnum;
import com.fqgj.msg.push.AppsFlyerService;
import com.fqgj.msg.ro.AppsFlyerContentRO;
import com.fqgj.msg.ro.SingleBuryingPointRequestRO;
import com.fqgj.msg.ro.SingleSmsSendRequestRO;
import com.fqgj.msg.sms.SmsMsgService;
import com.fqgj.msg.utils.Result;
import com.fqgj.xjd.user.client.UserEmailService;
import com.fqgj.xjd.user.client.UserService;
import com.fqgj.xjd.user.client.response.UserAuthEmail;
import com.google.common.base.Strings;
import com.qianli.cashmama.product.facade.result.AppPackageInfo;
import com.qianli.cashmama.trade.common.enums.message.MessageSceneEnum;
import com.qianli.cashmama.trade.common.utils.DateUtils;
import com.qianli.cashmama.trade.common.utils.HttpUtil;
import com.qianli.cashmama.trade.common.utils.TradeConfigUtil;
import com.qianli.cashmama.trade.integration.notification.message.MessageIntegrationService;
import com.qianli.cashmama.trade.integration.notification.message.dto.BillNoteMsgDto;
import com.qianli.cashmama.trade.integration.notification.message.dto.RepaymentMsgDto;
import com.qianli.cashmama.trade.integration.notification.message.utils.MessageUtils;
import com.qianli.cashmama.trade.integration.notification.message.utils.PushUtils;
import com.qianli.cashmama.trade.vo.LoanAgainNotificationUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/8/8
 * Time: 下午3:55
 */
@Service
public class MessageIntegrationServiceImpl implements MessageIntegrationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageIntegrationServiceImpl.class);

    @Autowired
    private SmsMsgService smsMsgService;

    @Autowired
    private EmailSendService emailSendService;

    @Autowired
    private UserEmailService userEmailService;

    @Autowired
    private TradeConfigUtil configUtil;

    @Autowired
    private PushUtils pushUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageUtils messageUtils;

    @Autowired
    private AppsFlyerService appsFlyerService;

    @Override
    public boolean loanSuccessNote(String userCode, String tradeNo, String mobile, String bankNo, String userName, String nbfcName, String borrowTotalCapital) {
        try {
            LOGGER.info("放款发送短信参数,tradeNo:{}", tradeNo);
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            singleSmsSendRequestRO.setPhone(mobile);

            Map<String, String> replaceParam = new HashMap<>();
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_PAYMENT_NONE);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            replaceParam.put("name", userName);
            replaceParam.put("bankNo", bankNo.substring(bankNo.length() - 4));

            singleSmsSendRequestRO.setReplaceParam(replaceParam);
            singleSmsSendRequestRO.setUserCode(userCode);

            LOGGER.info("放款成功发送短信参数,singleSmsSendRequestRO:{}", JSON.toJSONString(singleSmsSendRequestRO));
            smsMsgService.send(singleSmsSendRequestRO).getData();
        } catch (Exception e) {
            LOGGER.error("放款结果短信发送失败,loanNoteDto:" + JSON.toJSONString(tradeNo), e);
        }

        try {
            String url = messageUtils.getEmailBasicTemplateUrl(userCode, tradeNo);
            String content = HttpUtil.getPage(url);
            content = content.replace("__content__", configUtil.getPaymentEmailContent());
            content = content.replace("__NBFC NAME__", nbfcName);
            content = content.replace("__Users Name__", Strings.nullToEmpty(userName));
            content = content.replace("__Mobile No.__", Strings.nullToEmpty(mobile));
            content = content.replace("__Order ID__", Strings.nullToEmpty(tradeNo));

            content = content.replaceAll("__Amount__", borrowTotalCapital);
            content = content.replaceAll("__Date__", DateUtil.getDateTime("dd/MM/YYY", new Date()));
            loanNoteByEmail(userCode, tradeNo, content, "Loan successfully Disbursed");
        } catch (Exception e) {
            LOGGER.error("send email failed,tradeNo:" + tradeNo, e);
        }

        return true;
    }

    /**
     * 放款失败触发重绑卡短信
     *
     * @param userCode
     * @param tradeNo
     * @param mobile
     * @param bankNo
     * @param userName
     * @return
     */
    @Override
    public boolean loanFailAndRebindNote(String userCode, String tradeNo, String mobile, String bankNo, String userName) {
        if (!configUtil.getTradePaymentFailureMsgSwitch()) {
            LOGGER.info("loanFailAndRebindNote,暂停发短信,tradeNo:{},mobile:{}", tradeNo, mobile);
            return true;
        }
        //发送短信
        try {
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            Map<String, String> params = new HashMap<>();
            params.put("name", userName);
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_PAYMENT_FAILURE);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(mobile);
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(userCode);
            smsMsgService.send(singleSmsSendRequestRO).getData();
            LOGGER.info("loanFailAndRebindNote,用户打款失败发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("用户打款失败发送短信失败", e);
        }
        return true;
    }

    @Override
    public boolean sendBillNote(BillNoteMsgDto billNoteMsgDto) {
        LOGGER.info("sendMsg failed,billNoteMsgDto:{}", JSON.toJSONString(billNoteMsgDto));
        try {
            String taskSwitch = configUtil.messageSwitch();
            if (StringUtils.isEmpty(taskSwitch) || taskSwitch.equals("0")) {
                LOGGER.info("== 短信发送开关未开启==");
                return false;
            }
            // 还款日期
            Date repaymentDate = TimeUtils.getDate("yyyy-MM-dd", billNoteMsgDto.getRepaymentDate());
            Date nowDate = TimeUtils.getDate("yyyy-MM-dd", new Date());

            // 发送邮件及push消息
            pushWillExpireMsg(billNoteMsgDto, repaymentDate, nowDate);

            // 发送短信
            return sendMsg(billNoteMsgDto, repaymentDate, nowDate);
        } catch (Exception e) {
            LOGGER.error("sendMsgFailed,billNoteMsgDto:{}", JSON.toJSONString(billNoteMsgDto), e);
            LOGGER.error("sendMsgFailed", e);
            return false;
        }
    }

    /**
     * 还款短信通知
     *
     * @param billNoteMsgDto
     * @param repaymentDate
     * @param nowDate
     * @return
     */
    private boolean sendMsg(BillNoteMsgDto billNoteMsgDto, Date repaymentDate, Date nowDate) {
        Map<String, String> params = new HashMap<>();
        String date = DateUtil.getDate(billNoteMsgDto.getRepaymentDate(), "dd-MM-yyyy");
        SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();

        String userName = Optional.ofNullable(userService.getUserByUserCode(billNoteMsgDto.getUserCode()))
                .filter(Response::isSuccess)
                .map(userResponse -> userResponse.getData().getName()).orElse("");
        if (repaymentDate.compareTo(nowDate) == 0) { // 当天
            // send mail
            params.put("totalAmount", billNoteMsgDto.getBorrowTotalCapital());
//            params.put("amount", billNoteMsgDto.getRepaymentCapital());
            params.put("name", userName);

            String bizCode = messageUtils.getMessageBizCodeByPackageName(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), MessageSceneEnum.SMS_REPAYMENT_REMINDER);
            singleSmsSendRequestRO.setBizCode(bizCode);
        } else if (DateUtil.addDate(repaymentDate, -1).compareTo(nowDate) == 0) { // 提前一天
            params.put("name", userName);
            params.put("totalAmount", billNoteMsgDto.getBorrowTotalCapital());
//            params.put("amount", billNoteMsgDto.getRepaymentCapital());
            params.put("date", date);
            String bizCode = messageUtils.getMessageBizCodeByPackageName(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), MessageSceneEnum.SMS_REPAYMENT_REMINDER_ADVANCE_1DAY);
            singleSmsSendRequestRO.setBizCode(bizCode);
        } else if (DateUtil.addDate(repaymentDate, -3).compareTo(nowDate) == 0) { // 提前两天
            params.put("userName", userName);
            params.put("days", "3days");
            String bizCode = messageUtils.getMessageBizCodeByPackageName(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), MessageSceneEnum.SMS_REPAYMENT_REMINDER_ADVANCE_2DAY);
            singleSmsSendRequestRO.setBizCode(bizCode);
        }
        singleSmsSendRequestRO.setPhone(billNoteMsgDto.getMobile());
        singleSmsSendRequestRO.setReplaceParam(params);
        singleSmsSendRequestRO.setUserCode(billNoteMsgDto.getUserCode());
        return smsMsgService.send(singleSmsSendRequestRO).getData();
    }

    private void pushWillExpireMsg(BillNoteMsgDto billNoteMsgDto, Date repaymentDate, Date nowDate) {
        try {
            String pushContent = configUtil.msgpushbillremindertoday() ;
            // push
            String[] split = pushContent.split("\\|");
            String title = split[0];
            String content = split[1];
            content = content.replace("##AMOUNT##", billNoteMsgDto.getBorrowTotalCapital());
            content = content.replace("##REPAID##", billNoteMsgDto.getRepaymentCapital());
            String jumpPage = split[2];

            if (repaymentDate.compareTo(nowDate) == 0) {
                pushUtils.singlePush(billNoteMsgDto.getUserCode(), title, content, jumpPage);
                sendMailToday(billNoteMsgDto);
            } else if (DateUtil.addDate(repaymentDate, -1).compareTo(nowDate) == 0) { // 提前一天
                sendMail1Days(billNoteMsgDto);
            } else if (DateUtil.addDate(repaymentDate, -3).compareTo(nowDate) == 0) {  // 提前两天
                sendMail3Days(billNoteMsgDto);
                content = configUtil.msg_push_bill_reminder_3days();
                pushUtils.singlePush(billNoteMsgDto.getUserCode(), title, content, jumpPage);
            }
        } catch (Exception e) {
            LOGGER.error("发送push失败,billNoteMsgDto:" + JSON.toJSONString(billNoteMsgDto), e);
        }
    }

    private void sendMailToday(BillNoteMsgDto billNoteMsgDto) {
        try {
            Optional.ofNullable(userService.getUserByUserCode(billNoteMsgDto.getUserCode())).filter(Response::isSuccess)
                    .map(Response::getData).ifPresent(user -> {
                String basicTemplateUrl = messageUtils.getEmailBasicTemplateUrl(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo());
                String mainContent = configUtil.email_push_bill_reminder_content();
                String content = HttpUtil.getPage(basicTemplateUrl);
                content = content.replace("__content__", mainContent);
                content = content.replace("__Users Name__", Strings.nullToEmpty(billNoteMsgDto.getUserName()));
                content = content.replace("__Mobile No.__", Strings.nullToEmpty(billNoteMsgDto.getMobile()));
                content = content.replace("__Order ID__", Strings.nullToEmpty(billNoteMsgDto.getTradeNo()));
                content = content.replace("__amount__", billNoteMsgDto.getBorrowTotalCapital());
                content = content.replace("__repaid__", billNoteMsgDto.getRepaymentCapital());
                loanNoteByEmail(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), content, "Bill Reminder");
            });
        } catch (Exception e) {
            LOGGER.error("send mail failed", e);
        }
    }


    private void sendMail1Days(BillNoteMsgDto billNoteMsgDto) {

        try {
            Optional.ofNullable(userService.getUserByUserCode(billNoteMsgDto.getUserCode())).filter(Response::isSuccess)
                    .map(Response::getData).ifPresent(user -> {
                String basicTemplateUrl = messageUtils.getEmailBasicTemplateUrl(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo());
                String mainContent = configUtil.email_push_bill_reminder_content();

                String content = HttpUtil.getPage(basicTemplateUrl);
                content = content.replace("__content__", mainContent);
                content = content.replace("__Users Name__", Strings.nullToEmpty(billNoteMsgDto.getUserName()));
                content = content.replace("__Mobile No.__", Strings.nullToEmpty(billNoteMsgDto.getMobile()));
                content = content.replace("__Order ID__", Strings.nullToEmpty(billNoteMsgDto.getTradeNo()));

                content = content.replace("__repaid__", billNoteMsgDto.getRepaymentCapital());
                content = content.replace("__amount__", billNoteMsgDto.getBorrowTotalCapital());
                String format = new SimpleDateFormat("MMM dd", Locale.ENGLISH).format(billNoteMsgDto.getRepaymentDate());
                content = content.replace("__repaid_day__", format);
                loanNoteByEmail(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), content, "Bill Reminder");

            });
        } catch (Exception e) {
            LOGGER.error("send mail failed", e);
        }
    }

    private void sendMail3Days(BillNoteMsgDto billNoteMsgDto) {
        try {
            Optional.ofNullable(userService.getUserByUserCode(billNoteMsgDto.getUserCode())).filter(Response::isSuccess)
                    .map(Response::getData).ifPresent(user -> {
                String basicTemplateUrl = messageUtils.getEmailBasicTemplateUrl(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo());

                String mainContent = configUtil.email_push_bill_reminder_3days_content();
                String content = HttpUtil.getPage(basicTemplateUrl);
                content = content.replace("__content__", mainContent);
                content = content.replace("__Users Name__", Strings.nullToEmpty(billNoteMsgDto.getUserName()));
                content = content.replace("__Mobile No.__", Strings.nullToEmpty(billNoteMsgDto.getMobile()));
                content = content.replace("__Order ID__", Strings.nullToEmpty(billNoteMsgDto.getTradeNo()));
                loanNoteByEmail(billNoteMsgDto.getUserCode(), billNoteMsgDto.getTradeNo(), content, "Bill Reminder");
            });
        } catch (Exception e) {
            LOGGER.error("send mail failed", e);
        }
    }

    /**
     * 还款完成短信通知
     *
     * @param repaymentMsgDto
     * @param userCode
     * @param tradeNo
     * @return
     */
    @Override
    public boolean sendRepaymentNote(RepaymentMsgDto repaymentMsgDto, String userCode, String tradeNo) {
        LOGGER.info("sendRepaymentNote,repaymentMsgDto:{}", JSON.toJSONString(repaymentMsgDto));
        try {
            Map<String, String> params = new HashMap<>();
//            params.put("totalAmount", repaymentMsgDto.getBorrowTotalCapital());
            params.put("name", repaymentMsgDto.getName());
            params.put("totalAmount", repaymentMsgDto.getRepaymentCapital());
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_REPAYMENT_NONE);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(repaymentMsgDto.getMobile());
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(userCode);
            return smsMsgService.send(singleSmsSendRequestRO).getData();
        } catch (Exception e) {
            LOGGER.info("sendMsg failed,repaymentMsgDto:{},e", JSON.toJSONString(repaymentMsgDto), e);
            return false;
        }
    }

    @Override
    public boolean loanNoteByEmail(String userCode, String tradeNo, String content, String title) {
        try {
            String appCode = messageUtils.getAppPackageInfoByUserCode(userCode, tradeNo).getAppCode();
            if (!configUtil.getNeedSendEmailAppCode().contains(appCode)) {
                LOGGER.info("不是cashmama不发邮件,{},userCode:{},appCode:{}", configUtil.getNeedSendEmailAppCode().toString(), userCode, appCode);
                return false;
            }

            UserAuthEmail authEmail = Optional.ofNullable(userEmailService.getUserEmail(userCode))
                    .filter(Response::isSuccess).map(Response::getData).orElseGet(UserAuthEmail::new);
            content = content.replace("__Email Id__", Strings.nullToEmpty(authEmail.getEmail()));
            content = content.replace("__Date__", DateUtil.getDate(new Date()));
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            singleSmsSendRequestRO.setPhone(authEmail.getEmail());
            Map<String, String> replaceParam = new HashMap<>();
            singleSmsSendRequestRO.setBizCode(messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.COMMON_EMAIL));
            singleSmsSendRequestRO.setTitle(title);
            replaceParam.put("content", content);
            singleSmsSendRequestRO.setReplaceParam(replaceParam);
            singleSmsSendRequestRO.setUserCode(userCode);
            LOGGER.info("放款发送邮件参数,singleSmsSendRequestRO:{}", JSON.toJSONString(singleSmsSendRequestRO));
            Result<Boolean> result = emailSendService.singleSend(singleSmsSendRequestRO);
            return result.getData();
        } catch (Exception e) {
            LOGGER.error("== 放放款发送邮件失败 ==,userCode:{}, content:{}", userCode, content, e);
            return false;
        }
    }

    /**
     * 发送再次借款通知消息
     *
     * @param loanAgainNotificationUserVO
     * @return
     */
    @Override
    public boolean sendLoanAgainNotification(LoanAgainNotificationUserVO loanAgainNotificationUserVO) {
        try {
            // 发送短信
            sendLoanAgainNotificationSms(loanAgainNotificationUserVO);

            // 发邮件
            sendLoanAgainNotificationEmail(loanAgainNotificationUserVO);
            return true;
        } catch (Exception e) {
            LOGGER.error("====== sendLoanAgainNotification exception, loanAgainNotificationUserVO:{} ======", JSONObject.toJSONString(loanAgainNotificationUserVO), e);
            return false;
        }
    }

    /**
     * 签约超时订单关闭通知用户
     *
     * @param userCode
     * @param tradeNo
     * @param name
     * @param mobile
     * @return
     */
    @Override
    public boolean sendSignTimeoutMessage(String userCode, String tradeNo, String name, String mobile) {
        try {
            Optional.ofNullable(userService.getUserByUserCode(userCode)).filter(Response::isSuccess)
                    .map(Response::getData).ifPresent(user -> {
                String basicTemplateUrl = messageUtils.getEmailBasicTemplateUrl(userCode, tradeNo);
                String mainContent = configUtil.getSignTimeoutRemindSms();
                String content = HttpUtil.getPage(basicTemplateUrl);
                content = content.replace("__content__", mainContent);
                content = content.replace("__Users Name__", Strings.nullToEmpty(name));
                content = content.replace("__Mobile No.__", Strings.nullToEmpty(mobile));
                content = content.replace("__Order ID__", Strings.nullToEmpty(tradeNo));
                loanNoteByEmail(userCode, tradeNo, content, "Sign Reminder");
            });
        } catch (Exception e) {
            LOGGER.error("send mail failed", e);
        }
        return true;
    }

    private void sendLoanAgainNotificationEmail(LoanAgainNotificationUserVO loanAgainNotificationUserVO) {
        String title = "CashMama Gentle Reminder";
        String basicTemplateUrl = messageUtils.getEmailBasicTemplate02Url(loanAgainNotificationUserVO.getUserCode(), null);
        String mainContent = configUtil.mail_send_loan_again_notification();
        String content = HttpUtil.getPage(basicTemplateUrl);
        content = content.replace("__content__", mainContent);
        content = content.replace("__Users Name__", Strings.nullToEmpty(loanAgainNotificationUserVO.getName()));
        content = content.replace("__Mobile No.__", Strings.nullToEmpty(loanAgainNotificationUserVO.getPhone()));

        loanNoteByEmail(loanAgainNotificationUserVO.getUserCode(), null, content, title);
    }

    private void sendLoanAgainNotificationSms(LoanAgainNotificationUserVO loanAgainNotificationUserVO) {
        try {
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            Map<String, String> params = new HashMap<>();
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(loanAgainNotificationUserVO.getUserCode(), null, MessageSceneEnum.SMS_LOAN_AGAIN);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(loanAgainNotificationUserVO.getPhone());
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(loanAgainNotificationUserVO.getUserCode());
            smsMsgService.send(singleSmsSendRequestRO).getData();
        } catch (Exception e) {
            LOGGER.error("====== sendLoanAgainNotificationSms exception, loanAgainNotificationUserVO:{} ======", JSONObject.toJSONString(loanAgainNotificationUserVO), e);
        }
    }

    /**
     * 信审通过发送消息
     *
     * @param tradeNo
     * @param userCode
     * @param mobile
     * @param name
     * @param borrowCapital
     */
    public void sendMessageAfterAuditPass(String tradeNo, String userCode, String mobile, String name, String borrowCapital) {
        if (!configUtil.getTradeAuditMsgSwitch()) {
            LOGGER.info("sendMessageAfterAuditPass,暂停发短信,tradeNo:{},mobile:{}", tradeNo, mobile);
            return;
        }
        //发送短信
        try {
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("totalAmount", borrowCapital);
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_AUDIT_PASS);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(mobile);
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(userCode);
            smsMsgService.send(singleSmsSendRequestRO).getData();
            LOGGER.info("sendMessageAfterAuditPass,信审通过发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("信审通过发送短信失败", e);
        }

        try {
            // push
            String pushContent = configUtil.getMsgPushLoanApproval();
            String[] split = pushContent.split("\\|");
            String title = split[0];
            String content = split[1];
            String jumpPage = split[2];
            pushUtils.singlePush(userCode, title, content, jumpPage);
            LOGGER.info("sendMessageAfterAuditPass,信审通过推送,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("信审通过发送推送失败," + tradeNo, e);
        }

        try {
            // 信审跳审通过
            String url = messageUtils.getEmailBasicTemplateUrl(userCode, tradeNo);
            String mailContent = HttpUtil.getPage(url);
            AppPackageInfo appPackageInfo = messageUtils.getAppPackageInfoByUserCode(userCode, tradeNo);
            mailContent = mailContent.replace("__content__", configUtil.getMailPushLoanApprovalContent(appPackageInfo.getAppName()));
            mailContent = mailContent.replace("__Users Name__", Strings.nullToEmpty(name));
            mailContent = mailContent.replace("__Mobile No.__", Strings.nullToEmpty(mobile));
            mailContent = mailContent.replace("__Order ID__", Strings.nullToEmpty(tradeNo));
            this.loanNoteByEmail(userCode, tradeNo, mailContent, "Loan Approval");
            LOGGER.info("sendMessageAfterAuditPass,信审通过发送邮件,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("信审通过发送邮件失败," + tradeNo, e);
        }
    }

    /**
     * 信审拒绝发送消息
     *
     * @param tradeNo
     * @param userCode
     * @param mobile
     * @param name
     * @param borrowCapital
     */
    @Override
    public void sendMessageAfterAuditRefuse(String tradeNo, String userCode, String mobile, String name, String borrowCapital) {
        if (!configUtil.getTradeAuditMsgSwitch()) {
            LOGGER.info("sendMessageAfterAuditRefuse,暂停发短信,tradeNo:{},mobile:{}", tradeNo, mobile);
            return;
        }
        //发送短信
        try {
            Map<String, String> paramMap = new HashMap<>();
            //短期拒绝14天后才能申请
            paramMap.put("name", name);
            paramMap.put("date", DateUtil.getDate(DateUtil.addDate(new Date(), 30), "dd-MM-yyyy"));
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_AUDIT_REJECT);
            SingleSmsSendRequestRO smsSendRequestRO = new SingleSmsSendRequestRO();
            smsSendRequestRO.setPhone(mobile);
            smsSendRequestRO.setBizCode(messageBizCode);
            smsSendRequestRO.setReplaceParam(paramMap);
            smsSendRequestRO.setUserCode(userCode);
            smsMsgService.send(smsSendRequestRO);
            LOGGER.info("sendMessageAfterAuditRefuse,信审拒绝发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("sendMessageAfterAuditRefuse", e);
        }

        try {
            // 信审拒绝
            Date date = DateUtil.addDate(new Date(), 30);
            String format = DateUtils.formatEnglishDate(date);
            String url = messageUtils.getEmailBasicTemplateUrl(userCode, tradeNo);
            String maincontent = HttpUtil.getPage(url);
            maincontent = maincontent.replace("__content__", configUtil.getMailPushLoanAuditRejectionContent());
            maincontent = maincontent.replace("__Users Name__", Strings.nullToEmpty(name));
            maincontent = maincontent.replace("__Mobile No.__", Strings.nullToEmpty(mobile));
            maincontent = maincontent.replace("__Order ID__", Strings.nullToEmpty(tradeNo));
            maincontent = maincontent.replace("__applyDate__", format);
            this.loanNoteByEmail(userCode, tradeNo, maincontent, "Loan Audit Rejection");
            LOGGER.info("sendMessageAfterAuditRefuse,信审拒绝发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("信审拒绝发送邮件失败," + tradeNo, e);
        }
    }

    /**
     * 需要用户操作highmark发送消息
     *
     * @param tradeNo
     * @param userCode
     * @param mobile
     * @param name
     * @param borrowCapital
     */
    @Override
    public void sendMessageAfterNeedHighmark(String tradeNo, String userCode, String mobile, String name, String borrowCapital) {
        if (!configUtil.getTradeAuditMsgSwitch()) {
            LOGGER.info("sendMessageAfterNeedHighmark,暂停发短信,tradeNo:{},mobile:{}", tradeNo, mobile);
            return;
        }
        //发送短信
        try {
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("totalAmount", borrowCapital);
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_HIGHMARK_REMIND);
            singleSmsSendRequestRO.setUserCode(userCode);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(mobile);
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(userCode);
            smsMsgService.send(singleSmsSendRequestRO).getData();
            LOGGER.info("sendMessageAfterNeedHighmark,等待highmark发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("等待highmark发送短信失败", e);
        }
    }

    /**
     * 需要用户提现发送消息
     *
     * @param tradeNo
     * @param userCode
     * @param mobile
     * @param name
     * @param borrowCapital
     */
    @Override
    public void sendMessageAfterNeedWithdraw(String tradeNo, String userCode, String mobile, String name, String borrowCapital) {
        if (!configUtil.getTradeAuditWithdrawMsgSwitch()) {
            LOGGER.info("sendMessageAfterNeedWithdraw,暂停发短信,tradeNo:{},mobile:{}", tradeNo, mobile);
            return;
        }
        //发送短信
        try {
            SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
            Map<String, String> params = new HashMap<>();
            params.put("name", name);
            params.put("totalAmount", borrowCapital);
            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_PENDING_WITHDRAWAL);
            singleSmsSendRequestRO.setBizCode(messageBizCode);
            singleSmsSendRequestRO.setPhone(mobile);
            singleSmsSendRequestRO.setReplaceParam(params);
            singleSmsSendRequestRO.setUserCode(userCode);
            smsMsgService.send(singleSmsSendRequestRO).getData();
            LOGGER.info("sendMessageAfterNeedWithdraw,用户提现发送短信,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("用户提现发送短信失败", e);
        }

        try {
            // 发邮件
            String url = messageUtils.getEmailBasicTemplateUrl(userCode, tradeNo);
            String mailContent = HttpUtil.getPage(url);
            AppPackageInfo appPackageInfo = messageUtils.getAppPackageInfoByUserCode(userCode, tradeNo);
            mailContent = mailContent.replace("__content__", configUtil.getMailPushLoanNeedWithdrawContent(appPackageInfo.getAppName()));
            mailContent = mailContent.replace("__Users Name__", Strings.nullToEmpty(name));
            mailContent = mailContent.replace("__Mobile No.__", Strings.nullToEmpty(mobile));
            mailContent = mailContent.replace("__Order ID__", Strings.nullToEmpty(tradeNo));
            mailContent = mailContent.replace("__APPNAME__", Strings.nullToEmpty(appPackageInfo.getAppName()));
            this.loanNoteByEmail(userCode, tradeNo, mailContent, "Pending withdrawal");
            LOGGER.info("sendMessageAfterNeedWithdraw,用户提现发送邮件,tradeNo:{},mobile:{}", tradeNo, mobile);
        } catch (Exception e) {
            LOGGER.error("用户待提现发送邮件失败," + tradeNo, e);
        }
    }

    @Override
    public void sendAppsflyerDataPush(String packageName, String appsflyerId, String userCode, String eventName, String eventValue) {
        AppsFlyerContentRO appsFlyerContentRO = new AppsFlyerContentRO();
        appsFlyerContentRO.setAppsflyerId(appsflyerId);
        appsFlyerContentRO.setCustomerUserId(userCode);
        appsFlyerContentRO.setEventName(eventName);
        appsFlyerContentRO.setEventValue(eventValue);
        appsFlyerContentRO.setEventCurrency("INR");
        appsFlyerContentRO.setEventTime(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));

        SingleBuryingPointRequestRO singleBuryingPointRequestRO = new SingleBuryingPointRequestRO();
        singleBuryingPointRequestRO.setAppId(packageName);
        singleBuryingPointRequestRO.setUserCode(userCode);
        singleBuryingPointRequestRO.setContent(JSONObject.toJSONString(appsFlyerContentRO));
        singleBuryingPointRequestRO.setEventName(eventName);
        singleBuryingPointRequestRO.setEventValue(eventValue);
        singleBuryingPointRequestRO.setBuryingPointServicerEnum(BuryingPointServicerEnum.APPS_FLYER);
        appsFlyerService.singleBuryingPoint(singleBuryingPointRequestRO);
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
    }
}
